﻿#pragma execution_character_set(“utf-8”)
#include "stdafx.h"
#include "QChatSrvDlg.h"
#include "QConnectionManager.h"
#include "QServerMsgManager.h"
#include "QMessageMaker.h"
#include "QActionDefines.h"


QChatSrvDlg::QChatSrvDlg(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::QChatSrvDlg())
{
    ui->setupUi(this);

    ui->textEdit->document()->setMaximumBlockCount(100);

    InitSlotFun();
}


QChatSrvDlg::~QChatSrvDlg()
{
    delete ui;
}

void QChatSrvDlg::OnStartSrv()
{
    QString strPort = ui->lineEditPort->text();
    int nPort = strPort.toInt();

    CloseConnect();

    if (m_pTcpServer == nullptr)
    {
        m_pTcpServer = new QTcpServer(this);
    }

    connect(m_pTcpServer, &QTcpServer::newConnection, this, &QChatSrvDlg::OnGetNewConnection);
    m_pTcpServer->listen(QHostAddress::Any, nPort);

    ui->textEdit->append(QObject::tr("服务开始"));

}

void QChatSrvDlg::OnStopSrv()
{
    // TODO: 关闭连接
}

void QChatSrvDlg::OnGetNewConnection()
{
    QTcpSocket* tcpSocket = m_pTcpServer->nextPendingConnection();

    //获取对方的IP和端口
    QString ip = tcpSocket->peerAddress().toString();

    QServerMsgManager& msgMgr = QServerMsgManager::GetInstance();
    connect(tcpSocket, &QTcpSocket::readyRead, &msgMgr, &QServerMsgManager::OnGetSockReadReady);

    QConnectionManager& connectMgr = QConnectionManager::GetInstance();
    connect(tcpSocket, &QTcpSocket::disconnected, &connectMgr, &QConnectionManager::OnSocketClosed);

    connect(&msgMgr, &QServerMsgManager::sigQueryUserName, this, &QChatSrvDlg::OnQueryUserName);
    connect(&msgMgr, &QServerMsgManager::sigLogin, this, &QChatSrvDlg::OnUserLogin);
    connect(&msgMgr, &QServerMsgManager::sigGetUserInfoList, this, &QChatSrvDlg::OnGetUserInfoList);
    connect(&msgMgr, &QServerMsgManager::sigSendUserMessage, this, &QChatSrvDlg::OnSendUserMessage);
}

void QChatSrvDlg::InitSlotFun()
{
    connect(ui->pushButtonStart, &QPushButton::clicked, this, &QChatSrvDlg::OnStartSrv);
    connect(ui->pushButtonStop, &QPushButton::clicked, this, &QChatSrvDlg::OnStopSrv);
}

void QChatSrvDlg::CloseConnect()
{
    if (m_pTcpServer == nullptr)
    {
        return;
    }

    m_pTcpServer->close();
    delete m_pTcpServer;
    m_pTcpServer = nullptr;
}

void QChatSrvDlg::OnQueryUserName(QTcpSocket* pSock, QString const& userName)
{
    QConnectionManager& connectMgr = QConnectionManager::GetInstance();

    if (userName.isEmpty())
    {
        return;
    }

    if (connectMgr.GetSockByUserName(userName) == nullptr)
    {
        QMessageMaker dataMaker;

        QString msg = dataMaker.MakeQueryUserNameResultMessage(true, userName, tr("ok"));

        QServerMsgManager::WriteSocketData(pSock, msg);
    }
    else
    {
        QMessageMaker dataMaker;

        QString msg = dataMaker.MakeQueryUserNameResultMessage(false, userName, tr("用户名已经存在"));

        QServerMsgManager::WriteSocketData(pSock, msg);
    }
}

void QChatSrvDlg::OnUserLogin(QTcpSocket* pSock, QString const& userName)
{
    QConnectionManager& connectMgr = QConnectionManager::GetInstance();

    if (!connectMgr.GetSockByUserName(userName))
    {
        LoginInfo logInfo;
        logInfo.userName = userName;
        logInfo.token = QUuid::createUuid().toString();
        connectMgr.SetInfoByConnection(pSock, logInfo);

        QMessageMaker dataMaker;
        QString msg = dataMaker.MakeLoginResultMessage(true, userName, logInfo.token, "ok");
        QServerMsgManager::WriteSocketData(pSock, msg);
    }
    else
    {
        QMessageMaker dataMaker;
        QString msg = dataMaker.MakeLoginResultMessage(false, userName, "", "用户已经存在");
        QServerMsgManager::WriteSocketData(pSock, msg);
    }
}

void QChatSrvDlg::OnGetUserInfoList(QTcpSocket* pSock, QString const& userName, QString const& token)
{
    QVector<UserInfo> res;
    QConnectionManager& connectMgr = QConnectionManager::GetInstance();

    QVector<LoginInfo> infoList = connectMgr.GetLoginInfoList();
    for (auto item : infoList)
    {
        UserInfo info;
        info.userName = item.userName;
        res.push_back(info);
    }

    QMessageMaker dataMaker;
    QString msg = dataMaker.MakeGetUserInfoListResultMessage(true, userName, token, res, tr("ok"));

    QServerMsgManager::WriteSocketData(pSock, msg);
}

void QChatSrvDlg::OnSendUserMessage(QTcpSocket* pSock, QString const& userName, QString const& token, QString const& userMsg)
{
    QConnectionManager& connectMgr = QConnectionManager::GetInstance();

    QVector<LoginInfo> infoList = connectMgr.GetLoginInfoList();
    for (auto user : infoList)
    {
        if (QTcpSocket* pUserSock = connectMgr.GetSockByUserName(user.userName))
        {
            QMessageMaker dataMaker;
            QString msg = dataMaker.MakeGetMessage(userName, userMsg);

            QServerMsgManager::WriteSocketData(pUserSock, msg);
        }
    }
}
